
using Qdb;
using Qdb.CS.Config;
using Qdb.CS.Internal;
using Qdb.CS.Internal.Config;
using Qdb.Ext;
using Qdb.Internal;

namespace Qdb.CS.Internal.Config
{
	/// <exclude></exclude>
	public class StandardClientServerFactory : IClientServerFactory
	{
		/// <exception cref="Qdb.Ext.QdbIOException"></exception>
		/// <exception cref="Qdb.Ext.OldFormatException"></exception>
		/// <exception cref="Qdb.Ext.InvalidPasswordException"></exception>
		public virtual IObjectContainer OpenClient(IClientConfiguration clientConfig, string
			 hostName, int port, string user, string password)
		{
			if (user == null || password == null)
			{
				throw new InvalidPasswordException();
			}
			Config4Impl config = AsLegacy(clientConfig);
			Config4Impl.AssertIsNotTainted(config);
			Socket4Adapter networkSocket = new Socket4Adapter(clientConfig.Networking.SocketFactory
				, hostName, port);
			return new ClientObjectContainer(clientConfig, networkSocket, user, password, true
				);
		}

		/// <exception cref="Qdb.Ext.QdbIOException"></exception>
		/// <exception cref="Qdb.Ext.IncompatibleFileFormatException"></exception>
		/// <exception cref="Qdb.Ext.OldFormatException"></exception>
		/// <exception cref="Qdb.Ext.DatabaseFileLockedException"></exception>
		/// <exception cref="Qdb.Ext.DatabaseReadOnlyException"></exception>
		public virtual IObjectServer OpenServer(IServerConfiguration config, string databaseFileName
			, int port)
		{
			LocalObjectContainer container = (LocalObjectContainer)QdbFactory.OpenFile(AsLegacy
				(config), databaseFileName);
			if (container == null)
			{
				return null;
			}
			lock (container.Lock())
			{
				return new ObjectServerImpl(container, config, port);
			}
		}

		private Config4Impl AsLegacy(object config)
		{
			return QdbClientServerLegacyConfigurationBridge.AsLegacy(config);
		}
	}
}
